package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.common.bean.PageParamVo;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.pms.entity.SkuAttrValueEntity;
import com.atguigu.gmall.pms.entity.SkuImagesEntity;
import com.atguigu.gmall.pms.entity.SpuAttrValueEntity;
import com.atguigu.gmall.pms.entity.SpuEntity;
import com.atguigu.gmall.pms.feign.GmallSmsClient;
import com.atguigu.gmall.pms.mapper.SkuMapper;
import com.atguigu.gmall.pms.mapper.SpuMapper;
import com.atguigu.gmall.pms.service.*;
import com.atguigu.gmall.pms.vo.SkuVo;
import com.atguigu.gmall.pms.vo.SpuAttrValueVo;
import com.atguigu.gmall.pms.vo.SpuVo;
import com.atguigu.gmall.sms.vo.SkuSaleVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service("spuService")
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {

    @Autowired
    private SpuDescService descService;

    @Autowired
    private SpuAttrValueService baseAttrService;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SkuImagesService imagesService;

    @Autowired
    private SkuAttrValueService attrValueService;

    @Autowired
    private GmallSmsClient smsClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public PageResultVo querySpusByCidAndPage(Long cid, PageParamVo pageParamVo) {
        QueryWrapper<SpuEntity> spuEntityQueryWrapper = new QueryWrapper<SpuEntity>();
        if (cid != 0) {
            spuEntityQueryWrapper.eq("category_id", cid);
        }
        String key = pageParamVo.getKey();

        if (StringUtils.isNotBlank(key)) {
            spuEntityQueryWrapper
                    .and(t -> t.eq("id", key).or().like("name", key));

        }
        IPage<SpuEntity> page = this.page(
                pageParamVo.getPage(),
                spuEntityQueryWrapper
        );

        return new PageResultVo(page);
    }

//    @Transactional(rollbackFor = Exception.class,timeout = 3)
    @GlobalTransactional
    @Override
    public void bigSave(SpuVo spu) {
        //1.先保存spu相关信息
        //1.1.保存spu pms_spu
        Long spuId = saveSpu(spu);

        //1.2.保存pms_spu_desc
        descService.saveSpuDesc(spu, spuId);
        //1.3.保存基本属性值 pms_spu_attr_value
        saveBaseAttrs(spu, spuId);
        //2.保存sku相关信息
        saveSku(spu, spuId);

        rabbitTemplate.convertAndSend("PMS_SPU_EXCHANGE","item.insert",spuId);
//        int i = 1/0;
    }

    private void saveSku(SpuVo spu, Long spuId) {
        List<SkuVo> skus = spu.getSkus();
        if (CollectionUtils.isEmpty(skus)){
            return;
        }
        //遍历每一个skuvo保存对应的信息
        skus.forEach(skuVo -> {
            //2.1.保存sku pms_sku
            skuVo.setSpuId(spuId);
            skuVo.setCategoryId(spu.getCategoryId());
            skuVo.setBrandId(spu.getBrandId());
            // 获取图片列表,并设置默认图片
            List<String> images = skuVo.getImages();
            if (!CollectionUtils.isEmpty(images)){
//                skuVo.setDefaultImage(images.get(0));
                skuVo.setDefaultImage(StringUtils.isBlank(skuVo.getDefaultImage())?images.get(0):skuVo.getDefaultImage());
            }
            skuMapper.insert(skuVo);
            Long skuId = skuVo.getId();
            //2.2.保存sku图片pms_sku_images
            if (!CollectionUtils.isEmpty(images)){
                //把图片地址集合转换成sku图片实体类集合,然后批量保存到sku图片表
                imagesService.saveBatch(images.stream().map(img->{
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setUrl(img);
                    skuImagesEntity.setSort(0);
                    skuImagesEntity.setDefaultStatus(StringUtils.equals(skuVo.getDefaultImage(),img)?1:0);
                    return skuImagesEntity;
                }).collect(Collectors.toList()));
            }
            //2.3.保存销售属性pms_sku_attr_value
            List<SkuAttrValueEntity> saleAttrs = skuVo.getSaleAttrs();

            saleAttrs.forEach(skuAttrValueEntity->{
                skuAttrValueEntity.setSkuId(skuId);
            });

            attrValueService.saveBatch(saleAttrs);
            //3.保存营销信息(skuId)
            SkuSaleVo skuSaleVo = new SkuSaleVo();
            BeanUtils.copyProperties(skuVo,skuSaleVo);
            skuSaleVo.setSkuId(skuId);
            smsClient.saveSkuSales(skuSaleVo);
        });
    }

    private void saveBaseAttrs(SpuVo spu, Long spuId) {
        List<SpuAttrValueVo> baseAttrs = spu.getBaseAttrs();
        if (!CollectionUtils.isEmpty(baseAttrs)) {
            baseAttrService.saveBatch(baseAttrs.stream().map(spuAttrValueVo -> {
                SpuAttrValueEntity spuAttrValueEntity = new SpuAttrValueEntity();
                BeanUtils.copyProperties(spuAttrValueVo, spuAttrValueEntity);
                spuAttrValueEntity.setSpuId(spuId);

                return spuAttrValueEntity;
            }).collect(Collectors.toList()));
        }
    }



    private Long saveSpu(SpuVo spu) {
        spu.setCreateTime(new Date());
        spu.setUpdateTime(spu.getCreateTime());
        this.save(spu);
        return spu.getId();
    }

}